package com.qianfeng.day30.controller;

import com.qianfeng.day30.entity.House;
import com.qianfeng.day30.entity.House_type;
import com.qianfeng.day30.service.HouseService;

import com.qianfeng.day30.service.House_typeService;
import com.qianfeng.day30.util.Constants;
import org.omg.CORBA.Request;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/house")
public class HouseController {
    @Resource
    private HouseService houseService;
    @Resource
    private House_typeService house_typeService;
    @RequestMapping("/list")
    public String list(Model model){
        List<House> houseList = houseService.findAll();
        model.addAttribute("houseList",houseList);
        return "/list";
    }
    @RequestMapping("/preAdd")
    public String preAdd(Model model){
        List<House_type> typeList = house_typeService.findAll();
        model.addAttribute("typeList",typeList);
        House house = new House();
        model.addAttribute("house",house);
        return "/add";
    }
    @RequestMapping("/add")
    public String add(House house, MultipartFile file) throws IOException {
        if(file!=null){
            String imagePath = UUID.randomUUID().toString();
            File newFile = new File(Constants.IMAGE_BASE_PATH+imagePath);
            file.transferTo(newFile);
            house.setHousePic(imagePath);
            houseService.save(house);
        }
        return "redirect:/house/list";
    }
    @RequestMapping("/list2")
    public String list2(Model model){
        List<House> houseList = houseService.findOrderBy();
        model.addAttribute("houseList",houseList);
        return "/list2";
    }
}
